<?php
declare(strict_types=1);
namespace app\admin\widget;
use aphp\core\Widget;
class ModelFieldOptions extends Widget
{
    protected string $tag = 'model_field';
    protected int $expire = 0;

    public function set($id = '', array $options = [])
    {
        $pre_options = $options['pre_options'] ?? []; // 前置选项
        $form_options =  db('model_field')->where('id', $id)->where('status=1')->value('form_options');
        if (empty($form_options)) {
            return $pre_options ?: ['未设置'];
        }
        // 关联表数据
        if (preg_match('/^(\w+)\.(\w+)=(\w+)@?(.*)$/', $form_options, $match)) {
            [,$table, $pk, $field, $where] = $match;
			return db($table)->where($where)->column($field, $pk);
        }
        // 调用控制器方法
        if (preg_match('/^action:(.*)$/', $form_options, $match)) {
            $data = action($match[1]);
            return is_array($data) ? $data : ['未设置'];
        }
        // 调用部件
        if (preg_match('/^widget:(.*)$/', $form_options, $match)) {
            $params = '';
            if (str_contains($match[1], '?')) {
                [$widget, $params] = explode('?', $match[1]);
            } else {
                $widget = $match[1];
            }
            $id = '';
            $options = [];
            if (!empty($params)) {
                parse_str($params, $options);
                if (isset($options['id'])) {
                    $id = $options['id'];
                    unset($options['id']);
                }
            }
            $data = widget($widget)->get($id, $options);
            return is_array($data) ? $data : ['未设置'];
        }
        $form_options = str_to_array($form_options);
        return $pre_options + $form_options;
    }
}